<template>
  <div class="template-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>模板管理</h2>
          <div class="header-actions">
            <el-button
                type="danger"
                :disabled="!selectedTemplates.length"
                @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button
                type="primary"
                :disabled="!selectedTemplates.length"
                @click="handleBatchToggle(true)"
            >
              批量启用
            </el-button>
            <el-button
                type="warning"
                :disabled="!selectedTemplates.length"
                @click="handleBatchToggle(false)"
            >
              批量禁用
            </el-button>
            <el-button type="primary" @click="showAddDialog">
              新增模板
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
            v-model="searchQuery"
            placeholder="搜索模板名称"
            clearable
            class="search-input"
            @input="handleSearch"
        />
      </div>

      <!-- 模板列表 -->
      <el-table
          v-loading="loading"
          :data="templates"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="templateName" label="模板名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
                v-model="scope.row.isEnabled"
                @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="showPreviewDialog(scope.row)"
            >
              预览
            </el-button>
            <el-button
                type="primary"
                link
                @click="showEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                link
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

      <!-- 预览对话框 -->
      <el-dialog
          v-model="previewDialogVisible"
          title="模板预览"
          width="60%"
      >
        <pre class="json-preview">{{ formatJSON(previewContent) }}</pre>
      </el-dialog>

      <!-- 模板编辑对话框 -->
      <el-dialog
          v-model="dialogVisible"
          :title="editingTemplate.id ? '编辑模板' : '新增模板'"
          width="60%"
      >
        <el-form
            ref="templateForm"
            :model="editingTemplate"
            :rules="rules"
            label-width="100px"
        >
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="editingTemplate.templateName" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
                v-model="editingTemplate.description"
                type="textarea"
                :rows="2"
            />
          </el-form-item>
          <el-form-item label="模板内容" prop="templateContent">
            <el-input
                v-model="editingTemplate.templateContent"
                type="textarea"
                :rows="10"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTemplateStore } from '@/stores/adminTemplate'
import {format} from "date-fns";
import { debounce } from 'lodash-es'

const selectedTemplates = ref([])
const previewDialogVisible = ref(false)
const previewContent = ref('')

const store = useTemplateStore()
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const templates = ref([])
const templateForm = ref(null)

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTemplates()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTemplates()
}

// 搜索防抖
const handleSearch = debounce(() => {
  currentPage.value = 1
  fetchTemplates()
}, 300)

// 监听搜索条件变化
watch(searchQuery, handleSearch)

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedTemplates.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
        `确定要删除选中的${selectedTemplates.value.length}个模板吗？`
    )
    const ids = selectedTemplates.value.map(item => item.id)
    await store.batchDeleteTemplates(ids)
    ElMessage.success('批量删除成功')
    await fetchTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量启用/禁用
const handleBatchToggle = async (enabled) => {
  try {
    const action = enabled ? '启用' : '禁用'
    await ElMessageBox.confirm(
        `确定要${action}选中的${selectedTemplates.value.length}个模板吗？`
    )
    const ids = selectedTemplates.value.map(item => item.id)
    await store.batchToggleStatus(ids, enabled)
    ElMessage.success(`批量${action}成功`)
    await fetchTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`批量${enabled ? '启用' : '禁用'}失败`)
    }
  }
}

// 预览模板
const showPreviewDialog = (template) => {
  previewContent.value = template.templateContent
  previewDialogVisible.value = true
}

// 格式化JSON显示
const formatJSON = (json) => {
  try {
    return JSON.stringify(JSON.parse(json), null, 2)
  } catch (e) {
    return json
  }
}

const formatTime = (time) => {
  if (!time) return '--'
  return format(new Date(time), 'yyyy年MM月dd日 HH时mm分ss秒')
}

const editingTemplate = reactive({
  id: null,
  templateName: '',
  description: '',
  templateContent: '',
  isEnabled: true
})

const rules = {
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  templateContent: [
    { required: true, message: '请输入模板内容', trigger: 'blur' }
  ]
}

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true
  try {
    const response = await store.getTemplateList({
      current: currentPage.value,
      size: pageSize.value,
      templateName: searchQuery.value
    })
    templates.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 保存模板
const handleSave = async () => {
  if (!templateForm.value) return

  await templateForm.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingTemplate.id) {
          await store.updateTemplate(editingTemplate)
        } else {
          await store.addTemplate(editingTemplate)
        }
        ElMessage.success('保存成功')
        dialogVisible.value = false
        await fetchTemplates()
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 显示编辑对话框
const showEditDialog = (template) => {
  Object.assign(editingTemplate, template)
  dialogVisible.value = true
}

// 显示新增对话框
const showAddDialog = () => {
  Object.assign(editingTemplate, {
    id: null,
    templateName: '',
    description: '',
    templateContent: '',
    isEnabled: true
  })
  dialogVisible.value = true
}

// 删除模板
const handleDelete = async (template) => {
  try {
    await ElMessageBox.confirm('确定要删除此模板吗？')
    await store.deleteTemplate(template.id)
    ElMessage.success('删除成功')
    await fetchTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 状态改变处理
const handleStatusChange = async (template) => {
  try {
    await store.toggleTemplateStatus(template.id, template.isEnabled)
    ElMessage.success('状态更新成功')
  } catch (error) {
    template.isEnabled = !template.isEnabled
    ElMessage.error('状态更新失败')
  }
}

onMounted(() => {
  fetchTemplates()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  gap: 10px;
}

.json-preview {
  white-space: pre-wrap;
  word-wrap: break-word;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-family: monospace;
}

.template-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>